package com.zq.springadmin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zq.springadmin.config.MenuHelper;
import com.zq.springadmin.dao.entity.Permission;
import com.zq.springadmin.exception.ResultException;
import com.zq.springadmin.mapper.PermissionMapper;
import com.zq.springadmin.mapper.RolePermissionMapper;
import com.zq.springadmin.service.IPermissionService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张乔
 * @since 2024-04-26
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    //    获取所有菜单
    @Override
    public List<Permission> getAll() {
        List<Permission> permissionList = this.list();
        if (CollectionUtils.isEmpty(permissionList)) {
            throw new ResultException(555, "当前没有开发出任何权限（菜单）");
        }
        // 构建树形结构
        List<Permission> buildTree = MenuHelper.BuildTree(permissionList);


        return buildTree;
    }

    //    删除菜单
    @Override
    public void removeByIdApi(Integer id) {

        int count = (int) this.count(new LambdaQueryWrapper<Permission>().eq(Permission::getParentId, id));
        if (count > 0) {
            throw new ResultException(501, "当前菜单下存在子菜单，无法删除");
        }
        this.removeById(id);     // 不存在子菜单直接删除


    }

    //增加菜单
    @Transactional
    @Override
    public void saveMenu(Permission permission) {

        // 添加新的节点
        this.save(permission);

        // 新添加一个菜单，那么此时就需要将该菜单所对应的父级菜单设置为半开
        updateSysRoleMenuIsHalf(permission);

    }


    @Resource
    private RolePermissionMapper rolePermissionMapper;

    private void updateSysRoleMenuIsHalf(Permission sysMenu) {

        // 查询是否存在父节点
        Permission permission = this.getOne(new LambdaQueryWrapper<Permission>().
                eq(Permission::getId, sysMenu.getParentId()));

        if (permission != null) {

            // 将该id的菜单设置为半开
rolePermissionMapper.updateSysRoleMenuIsHalf(permission.getId());

            // 递归调用
            updateSysRoleMenuIsHalf(permission);

        }

    }


}
